/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
const validate = require("./validate.js");
import __config from '@/config/env';

const formatTime = date => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(
		':');
};
const formatNumber = n => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};
//空值过滤器
const filterForm = form => {
	let obj = {};
	Object.keys(form).forEach(ele => {
		if (!validate.validatenull(form[ele])) {
			obj[ele] = form[ele];
		}
	});
	return obj;
};
//获取当前页面带参数的url
const getCurrentPageUrlWithArgs = val => {

	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const url = currentPage.route;
	const options = currentPage.options;
	let urlWithArgs = `/${url}?`;

	for (let key in options) {
		const value = options[key];
		urlWithArgs += `${key}=${value}&`;
	}

	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
	return urlWithArgs;
}
//获取url中的参数
const getUrlParam = (path, name) => {
	var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	if (reg.test(path))
		return unescape(RegExp.$2.replace(/\+/g, " "));
	return "";
}
//判断是否为微信浏览器中运行
const isWeiXinBrowser = () => {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	// #endif
	return false
}
//判断是否是小程序
const isMiniPg = () => {
	let isMiniPg = false
	//#ifdef MP-WEIXIN
	isMiniPg = true
	//#endif
	return isMiniPg
}
//获取客服端代码
const getClientCode = () => {
	let code = {}
	//#ifdef MP-WEIXIN
	code = {
		key: 'MP-WEIXIN',
		value: '微信小程序'
	}
	//#endif
	//#ifdef H5
	//普通H5
	code = {
		key: 'H5',
		value: '普通H5'
	}
	if (isWeiXinBrowser()) {
		//微信公众号H5
		code = {
			key: 'H5-WX',
			value: '公众号H5'
		}
	}
	//#endif
	return code
}
//重置url中的参数
const resetPageUrl = (query) => {
	var ary = [];
	for (var p in query) {
		if (query.hasOwnProperty(p) && query[p]) {
			ary.push(encodeURIComponent(p) + '=' + encodeURIComponent(query[p]));
		}
	}
	if (ary.length > 0) {
		let url = "?" + ary.join('&');
		history.replaceState(history.state, null, url); //替换页面显示url
	}
}

const imgUrlToBase64 = (imageUrl) => {
	return new Promise((resolve, reject) => {
		try {
			uni.downloadFile({
				url: imageUrl + '?s=' + Math.random().toString(),
				success: res => {
					if (res.statusCode === 200) {
						// uni 如果是H5或者APP会自动转为base64返回
						resolve(res.tempFilePath);
					} else {
						reject(res.errMsg);
					}
				},
				fail(err) {
					reject(err);
				}
			});
		} catch (e) {
			console.log(e)
			resolve(imageUrl);
		}
	})
}

// 设置原生app的分享url为h5的地址url
const setAppPlusShareUrl = query => {
	const pages = getCurrentPages();
	const curPage = pages[pages.length - 1];
	const userInfo = uni.getStorageSync('user_info')
	const userCode = userInfo ? userInfo.userCode : ''
	let component_appid = ""
	if (query && query.componentAppId) {
		component_appid = "&component_appid=" + query.componentAppId
	}
	let fullPath = curPage.$page.fullPath
	//判断是否有问号
	fullPath = fullPath.indexOf('?') != -1 ? fullPath + '&' : fullPath + '?'
	if (userCode) {
		return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
			'&sharer_user_code=' + userCode + component_appid;
	} else {
		return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
			component_appid
	}
};

// 设置原生app的分享url为h5的地址url（用于分销，默认首页地址）
const setAppPlusHomeShareUrl = query => {
	const userInfo = uni.getStorageSync('user_info')
	const userCode = userInfo ? userInfo.userCode : ''
	let component_appid = ""
	if (query && query.componentAppId) {
		component_appid = "&component_appid=" + query.componentAppId
	}
	let fullPath = '/pages/home/index?'
	if (userCode) {
		return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
			'&sharer_user_code=' + userCode + component_appid;
	} else {
		return __config.h5HostUrl + fullPath + 'tenant_id=' + __config.tenantId + '&app_id=' + __config.wxAppId +
			component_appid
	}
};

// 设置h5的分享地址url
const setH5ShareUrl = val => {
	const userInfo = uni.getStorageSync('user_info')
	const userCode = userInfo ? userInfo.userCode : ''
	let url = window.location.href
	// 如果没有 sharer_user_code 就添加，如果有就替换为自己的userCode
	if (userCode) {
		let index = url.indexOf('&sharer_user_code=')
		if (index == -1) {
			url = url + '&sharer_user_code=' + userCode;
		} else {
			let urlTemp = url.slice(0, index);
			url = urlTemp + '&sharer_user_code=' + userCode;
		}
	}
	return url
}

// 设置H5的分享url（用于分销，默认首页地址）
const setH5HomeShareUrl = val => {
	const userInfo = uni.getStorageSync('user_info')
	const userCode = userInfo ? userInfo.userCode : ''
	// 如果没有 sharer_user_code 就添加
	let url = window.location.origin + window.location.search;
	if (userCode) {
		let index = url.indexOf('&sharer_user_code=')
		if (index == -1) {
			url = url + '&sharer_user_code=' + userCode;
		} else {
			let urlTemp = url.slice(0, index);
			url = urlTemp + '&sharer_user_code=' + userCode;
		}
	}
	return url
}
// 获取当前页面路由或 path
const getCurPage = pages => {
	let curPage = pages[pages.length - 1];
	return curPage.route
}
// 保存别人分享来的 userCode
const saveSharerUserCode = options => {
	if (options.scene) {
		//接受二维码中参数
		/**
		 * 这里需要特别注意：
		 * 由于腾讯限制了scenes的长度，导致传参的局限性，为尽可能的利用这有限的长度传参，
		 * 故我们定义了scenes的参数格式，当一个页面需要传多个参数时，我们用“&”符号分割开来，第2位固定放分享人的user_code，这样可以最大限度减少长度占用
		 * 第1位一般放ID，第2位固定放分享人的user_code，比如商品页面scenes为：goodspuId+&+sharer_user_code
		 * 因为固定第2位放分享人的user_code，当有些页面无需传ID时，我们也需要用“&”拼一下，第一位随意用一个字符点位即可，比如页面scenes为：0+&+sharer_user_code
		 */
		let scenes = decodeURIComponent(options.scene).split('&');
		if (scenes[1]) {
			uni.setStorageSync('sharer_user_code', scenes[1]);
		}
	} else {
		if (options.sharer_user_code) {
			uni.setStorageSync('sharer_user_code', '');
			uni.setStorageSync('sharer_user_code', options.sharer_user_code);
		}
	}

}

// 如果有分享人则给data带上分享人的user_code
const dataAddSharerUserCode = data => {
	let sharer_user_code = uni.getStorageSync('sharer_user_code')
	if (sharer_user_code) {
		data = Object.assign({
			sharerUserCode: sharer_user_code
		}, data)
	}
	return data
}

//返回登录页面
const backLoginPage = data => {
	var pages = getCurrentPages(); // 获取页面栈
	var currPage = pages[pages.length - 1]; // 当前页面
	if (currPage) {
		let curParam = currPage.options
		// 拼接参数
		let reUrl = '/' + currPage.route
		if (curParam != null) {
			// 拼接参数
			let param = ''
			for (let key in curParam) {
				param += '&' + key + '=' + curParam[key]
			}
			param = param.substr(1)
			reUrl = reUrl + '?' + param
			reUrl = encodeURIComponent(reUrl)
		}
		uni.reLaunch({
			url: '/pages/login/index?reUrl=' + reUrl
		});
	}
}

/**
 * 跳转到页面栈中已存在的页面时，直接返回到该页面中去
 */
const goNavigatePage = url => {
	const paramsIndex = url.indexOf('?')
	// 要调整的url
	const goUrl = paramsIndex > -1 ? url.substring(0, paramsIndex) : url
	let delta = 0
	let hasUrl = false
	let pages = getCurrentPages()
	pages.reverse().forEach((item) => {
		let page = '/' + item.route
		if (page == goUrl) {
			hasUrl = true
			return
		} else if (!hasUrl) {
			delta++
		}
	})
	if (hasUrl) {
		uni.navigateBack({
			delta: delta
		})
	} else {
		uni.navigateTo({
			url: url
		})
	}
}


module.exports = {
	formatTime: formatTime,
	filterForm: filterForm,
	getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
	getUrlParam: getUrlParam,
	isWeiXinBrowser: isWeiXinBrowser,
	isMiniPg: isMiniPg,
	resetPageUrl: resetPageUrl,
	getClientCode: getClientCode,
	imgUrlToBase64: imgUrlToBase64,
	setAppPlusShareUrl: setAppPlusShareUrl,
	setH5ShareUrl: setH5ShareUrl,
	getCurPage: getCurPage,
	saveSharerUserCode: saveSharerUserCode,
	dataAddSharerUserCode: dataAddSharerUserCode,
	backLoginPage: backLoginPage,
	setAppPlusHomeShareUrl,
	setH5HomeShareUrl,
	goNavigatePage,
};
